;
(function() {

	//返回相应的指令来进行分别执行
	module.exports = {
		"订单-单个商品-打折": function(args) {
			var ach = AchCon.get(args.ach_id);
			var goods = GoodsCon.get(args.goods_id);
			var buff = BuffCon.getInstance(this);
			//可能数量上有限定，或者阶梯性的打折
			ach.cash -= goods.price * buff.config.discount * args.num;
			ach.save();
		},
		"订单-多个商品-打折": function(args) {

		},
		//需要price，num
		"单个商品-打折": function(args) {
			var goods = GoodsCon.getAlone(args.goods_id);
			goods.cash = this.config.discount * goods.price;
			console.log(goods.cash);
			goods.save();
		},
		"多个商品-打折": function(args) {
			console.log(this, args);
		},
		"积分抵现": function(args) {
			console.log(this, args);
		},
		//需要price
		"推荐返利": function(args) {
			console.log("推荐返利触发~~~", args.env, args.callBy);
			if (args.env === BuffCon.env.inOnlinePayAch || args.env === BuffCon.env.inCashPay) {
				//已经生成订单，未付款，计算订单价格
				var ach = AchCon.get(args.ach_id);
				var bus = BusCon.get(ach.info.bus_id);
				var recommender = ach.info.recommender_id && UserCon.get(ach.info.recommender_id);
				if (recommender) { //如果有推荐者，查看是否有配置推荐返利的优惠
					var sou_cash = ach.sou_cash;
					//先扣除那些无法使用推荐返利的商品价格

					//商品二进制
					ach.info.goods_info.forEach(function(goods_and_num) {
						var goods_id = goods_and_num.goods._id;
						if (bus.isBinaGoods(goods_id)) {
							var bina = BinaCon.build(goods_id);
							//购买者是否还未购买过此商品
							if (!bina.hasBuyed(ach.info.user_id)) {
								//如果是第一次购买，无法使用推荐返利，而是使用商品二进制
								sou_cash -= goods_and_num.goods.cash * goods_and_num.num;
							}
						}
					});
					//判断是否是导购员（员工），是的话用导购员的配置
					var _is_guider = bus.isGuideUser(ach.info.recommender_id);
					var recommend_config = _is_guider ? bus.getGuideConfig() : bus.getRecommendConfig();
					for (var i = recommend_config.length - 1, recommend_config_item; recommend_config_item = recommend_config[i]; i -= 1) {
						if (recommend_config_item.max_price <= sou_cash) {
							break;
						}
					}
					if (recommend_config_item) {
						// console.log("sou_cash:", sou_cash, _is_guider, bus.getGuideConfig(), bus.getRecommendConfig())
						ach.cash -= sou_cash * recommend_config_item.hasOwnProperty("disc_rate") ? recommend_config_item.disc_rate : recommend_config_item.rate;
						ach.save();
					}
				}
			}

			//需要正确的触发环境才能触发，这个BUFF需要在订单生成的时候才能进行触发
			//支付完成后绑定积分关系
			if (args.env === BuffCon.env.afterPayAch) {
				var ach = AchCon.get(args.ach_id);
				var bus = BusCon.get(ach.info.bus_id);
				var recommender = ach.info.recommender_id && UserCon.get(ach.info.recommender_id);
				console.log("recommender_id", ach.info.recommender_id);
				if (recommender) {
					var bind_id = BusUserBindCon.build({
						user_id: recommender._id,
						bus_id: bus._id
					});
					var user_id = ach.info.user_id;
					var bind = BusUserBindCon.get(bind_id);
					var ach_推荐返利_cash = ach.cash; //不管自定义价格，就单单算订单的价值
					console.log("START:ach_推荐返利_cash:", ach_推荐返利_cash);
					var _can_multi_bina = !!bus.getPerm().can_multi_bina;
					ach.info.goods_info.forEach(function(goods_and_num) {
						var goods_id = goods_and_num.goods._id;
						if (bus.isBinaGoods(goods_id)) {
							var bina = BinaCon.build(goods_id);
							if (!bina.hasBuyed(user_id) || _can_multi_bina) {
								var _current_cut_cash = goods_and_num.goods.cash * (_can_multi_bina ? goods_and_num.num : 1);
								console.log("\t_current_cut_cash:", _current_cut_cash);
								ach_推荐返利_cash -= _current_cut_cash;
							}
						}
					});
					console.log("END:ach_推荐返利_cash:", ach_推荐返利_cash);
					var _cash = ach_推荐返利_cash * 1 /*这里默认为1，后面可能要根据商品来做出特殊调整，而非固定“￥1=1积分”*/
					bind._addAchs(ach._id, _cash);
				}
			}
		},
		"导购返利": function(args) {
			//支付完成后绑定导购者的积分关系
			if (args.env === BuffCon.env.afterPayAch) {
				console.log("导购返利触发~~", args.env, args.callBy);
				var ach = AchCon.get(args.ach_id);
				var bus = BusCon.get(ach.info.bus_id);
				var guide = BusGuideCon.get(ach.info.guide_id);
				if (guide && (guide = guide.getDetail())) {
					//将成交记录加入到导购列表中
					guide._addAch(ach._id, ach.cash * 1 /*默认为1*/ );
				}
			}
		},
		"抵用卷抵现": function(args) {
			var ach = AchCon.get(args.ach_id);
			ach.cash -= this.config.vm_cash;
			ach.save();
			// //将这次BUFF的运作信息复制并写入订单中
			// ach._addBuff(this._id);
		},
		"推荐-打折": function(args) {
			var ach = AchCon.get(args.ach_id);
			console.log(this.config.discount, ach.cash);
			ach.cash *= this.config.discount;

			// if (args.env == BuffCon.env.afterPayAch) {
			// 	var buff = this;
			// 	var AchCon = require("../ach/_con");
			// 	var UserCon = require("../user/_con");
			// 	var BusCon = require("../bus/_con");
			// 	var ach = AchCon.get(info.ach_id);
			// 	var recommender_id = ach.info.recommender_id;
			// 	var bus_id = ach.info.bus_id;
			// 	// var recommender = UserCon.get(recommender_id);
			// 	var bus = BusCon.get(bus_id);
			// 	var bind_id = BusUserBindCon.build({
			// 		user_id: recommender_id,
			// 		bus_id: bus_id
			// 	});
			// 	var bind = BusUserBindCon.get(bind_id);
			// 	bind._addAchs(ach._id, ach.cash * this.config.recInt_percent);
			// }
		},
		"优惠码": function(args) {
			if (args.env === BuffCon.env.inOnlinePayAch || args.env === BuffCon.env.inCashPay) {
				console.log("优惠码触发~~~", args.env, args.callBy);
				//已经生成订单，未付款
				var ach = AchCon.get(args.ach_id);
				var coupon = CouponCon.get(this.config.coupon_id);
				if (coupon) {
					if (coupon.info.type === CouponCon.TYPE.打折) {
						var discount = +coupon.info.config.discount;
						if (discount) {
							ach.cash -= ach.cash * (1 - discount);
							ach.save();
						}
					}
				}
			}
		},
		"优惠券": function(args) {
			if (args.env === BuffCon.env.inOnlinePayAch || args.env === BuffCon.env.inCashPay) {
				console.log("优惠券触发：", args.env, args.callBy);
				var ach = AchCon.get(args.ach_id);
				var ticket = TicketCon.get(this.config.ticket_id);
				if (ticket) {
					var ticket_config_info = ticket.ticket_factory.info;
					console.log(ticket_config_info)
					if (ticket_config_info.type === TicketFactoryCon.TYPE.满减) {
						var full_cash = +ticket_config_info.config.full_cash;
						var cut_cash = +ticket_config_info.config.cut_cash;
						if (full_cash <= ach.sou_cash) {
							ach.cash -= cut_cash;
							ach.save();
						}
					} else if (ticket_config_info.type === TicketFactoryCon.TYPE.打折) {
						var discount = +ticket_config_info.config.discount;
						if (discount) {
							ach.cash -= ach.cash * discount;
							ach.save();
						}
					} else if (ticket_config_info.type === TicketFactoryCon.TYPE.现金抵用) {
						var directly_cut_cash = +ticket_config_info.config.directly_cut_cash;
						if (directly_cut_cash) {
							ach.cash -= directly_cut_cash;
							ach.save();
						}
					}

				}
			}
		},
		"会员卡": function(args) {
			if (args.env === BuffCon.env.inOnlinePayAch || args.env === BuffCon.env.inCashPay) {
				console.log("会员卡触发：", args.env, args.callBy);
				var ach = AchCon.get(args.ach_id);
				var card_factory = CardFactoryCon.get(this.config.card_factory_id || this.config.card_id);
				if (card_factory) {
					var card_config_info = card_factory.info;
					console.log(card_config_info)
					if (card_config_info.type === CardFactoryCon.TYPE.满减) {
						var full_cash = +card_config_info.config.full_cash;
						var cut_cash = +card_config_info.config.cut_cash;
						if (full_cash <= ach.sou_cash) {
							ach.cash -= cut_cash;
							ach.save();
						}
					} else if (card_config_info.type === CardFactoryCon.TYPE.打折) {
						var discount = +card_config_info.config.discount;
						if (discount) {
							ach.cash -= ach.cash * discount;
							ach.save();
						}
					} else if (card_config_info.type === CardFactoryCon.TYPE.现金抵用) {
						var directly_cut_cash = +card_config_info.config.directly_cut_cash;
						if (directly_cut_cash) {
							ach.cash -= directly_cut_cash;
							ach.save();
						}
					}

				}
			}
		},
		"类目文件夹": function(args) {
			console.log("类目文件夹触发：", args.env, args.callBy);
			var goods = args.goods || GoodsCon.getAlone(args.goods_id);
			var classify = ClassifyCon.get(this.config.classify_id);
			if (!classify) {
				return
			}
			if (!classify.enable_buff) { //禁用状态，理论上是已经removeBuff了，这里判断着玩，肯定是true，不需要判断的
				return
			}
			var classify_info = classify.getBuffEnableInfo();
			if (!classify_info) { //找不到父级，GG
				return
			}

			console.log(classify_info._id, classify_info.type, classify_info.config);
			//公共专区的价格
			goods.cash = buff_code_helper.优惠通用算法({
				current_cash: goods.cash,
				sou_cash: goods.price
			}, classify_info, ClassifyCon.TYPE)

			//会员卡专区不同的价格
			var bus = BusCon.get(goods.bus_id);
			var card_factory_id_list = bus._getCardFactoryIdList();
			var card_cash_map = goods.card_cash_map || (goods.card_cash_map = {});
			card_factory_id_list.forEach(function(card_factory_id) {
				// 寻找优惠配置
				var classify_info_for_card_factory = classify.getBuffEnableInfoByCardFactoryId(card_factory_id) || classify_info;
				if (!classify_info_for_card_factory) {
					return;
				}
				card_cash_map[card_factory_id] = buff_code_helper.优惠通用算法({
					current_cash: card_cash_map[card_factory_id] || goods.price,
					sou_cash: goods.price
				}, classify_info_for_card_factory, ClassifyCon.TYPE);
				// card_cash_map
			});
		},
		"商品交易完成访问回调地址": function(args) {
			if (args.env === BuffCon.env.afterPayAch) {
				console.log("商品交易完成访问回调地址 触发", args.env, args.callBy);
				var bus = BusCon.get(args.bus_id);
				if (!bus.getPerm().can_set_goods_call_back_buff) {
					console.log("商家权限不足，无法使用这个功能思密达");
				} else {
					var cb_url = this.info.cb_url.format(args)
					console.log("支付完成啦，搞起：", cb_url);
					var post_options = url.parse(cb_url);
					post_options.method = "POST";
					post_options.headers = {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
					var time = +new Date;
					var info_args = this.info.args || "";
					var post_data = querystring.stringify({
						args: info_args,
						time: time,
						match_key: md5.md5_2(bus.info.password + info_args + time + cb_url)
					});
					console.log(post_data);
					var i = 0;

					function _send() {
						i += 1;
						if (i > 10) {
							console.log("回调错误过多，停止请求");
							midEvent.emit("ach.pay_end.call_back_url.error", args.ach_id, args.user_id)
							return;
						}
						var post_req = http.request(post_options, function(res) {
							res.setEncoding('utf8');
							var result = "";
							res.on('data', function(chunk) {
								result += chunk;
							});
							res.on("end", function() {
								if (result != "success") {
									console.log(result)
									console.info("回调错误，再次发起请求");
									setTimeout(_send, 10000);
								} else {
									console.log(args.ach_id, args.user_id)
									midEvent.emit("ach.pay_end.call_back_url.success", args.ach_id, args.user_id)
									console.log("回调指示正常，完成回调");
								}
							})
							res.on("error", _send);
						});
						post_req.write(post_data);
						post_req.end();
					}
					_send();
				}
				/*
				 * POST
				 * args:
				 */
			}
		},
		"商品二进制": function(args) {
			if (args.env === BuffCon.env.afterPayAch) {
				console.log("商品二进制 触发", args.env, args.goods_id, args.callBy);
				var goods = GoodsCon.get(args.goods_id);
				var ach = AchCon.get(args.ach_id);
				if (ach && goods && goods.is_bina) {
					var bina = BinaCon.build(args.goods_id, args.bus_id);
					bina.addAch(args.ach_id, this.config);
				}
			}
		},
		"商品返现": function(args) {
			if (args.env === BuffCon.env.afterPayAch) {
				var buff_config = this.config;
				var ach = AchCon.get(args.ach_id);
				var bus_user = BusUserCon.build({
					bus_id: ach.info.bus_id,
					user_id: ach.info.user_id
				}, true);
				var back_cash = 0;
				ach.info.goods_info.some(function(goods_and_num) {
					if (goods_and_num.goods._id === buff_config.goods_id) {
						back_cash = goods_and_num.num * buff_config.back_cash
						return true;
					}
				});
				bus_user._addMoney(back_cash, "商品（" + buff_config.goods_id + "）返现");
			}
		},
		"商品交易完成增加市代业绩": function(args) {
			if (args.env === BuffCon.env.afterPayAch) {
				console.log("触发增加市代业绩", args, this)
				var MA_user = UserCon.get(this.info.MA_user_id);
				if (!MA_user) {
					return
				}
				// console.log(MA_user.MA_map)
				var MA = MA_user.getMAByBusId(args.bus_id);
				// console.log("MA", MA);
				if (!MA) {
					return
				}
				//添加业绩
				MA._addAch(AchCon.get(args.ach_id));

				// 市代推荐人返利
				if (MA.introducer_id) {
					var bus_user = BusUserCon.build({
						bus_id: MA.bus_id,
						user_id: MA.introducer_id
					}, "get_instance");
					var ach = AchCon.get(args.ach_id);

					bus_user._addMoney(ach.finally_cash *
						BusCon.get(MA.bus_id).getMAConfig().recomment_MA_earn_rake / 100,
						"介绍的市代审核通过获得收益");

				}
			}
		}
	};
	//同名
	module.exports["商品分销"] = module.exports["商品二进制"]

	var db = require("../db/index");
	var BinaCon = require("../bina/_con");
	var CouponCon = require("../coupon/_con");
	var BusMACon = require("../bus.MA/_con");
	var ClassifyCon = require("../bus.classify/_con");
	var ClassifyCon = require("../bus.classify/_con");
	var TicketCon = require("../ticket/_con");
	var TicketFactoryCon = require("../ticket_factory/_con");
	var CardCon = require("../card/_con");
	var CardFactoryCon = require("../card_factory/_con");
	var UserCon = require("../user/_con");
	var BusCon = require("../bus/_con");
	var BusGuideCon = require("../bus.guide/_con");
	var GoodsCon = require("../goods/_con");
	var AchCon = require("../ach/_con");
	var PayAchCon = require("../pay_ach/_con");
	var CommentCon = require("../comment/_con");
	var EvaluationCon = require("../eval/_con");
	var ActivityCon = require("../league.activity/_con");
	var BusUserBindCon = require("../bus_user_bind/_con");
	var BusUserCon = require("../bus_user/_con");
	var BuffCon = require("./_con");
	var config = require("../_include/config");
	var data_cut = require("../_include/data_cut");
	var $Array = require("../_include/$.Array");
	var $Object = require("../_include/$.Object");
	var helper = require("../_include/helper");
	var db_table_name = config.dbname.buff;
	var db_id_prefix = config.dbIdPrefix.buff;
	var url = require("url");
	var querystring = require('querystring');
	var md5 = require("../_include/md5");
	var http = require("http");
	var midEvent = require("../../middleware/index");
	var buff_code_helper = require("./buff_code_helper");
}());